package com.sdusoft.action;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpSession;

import my.mvc.ActionException;
import my.mvc.RequestContext;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.sdusoft.beans.User;

public class UserAction {

	public void test(RequestContext ctx) throws IOException {
		System.out.println("-------------"+ctx.param("name"));
		// ctx.print("Ulric");
	}

	public void logout(RequestContext ctx) throws IOException {
		HttpSession session = ctx.session(false);
		//为了避免状态问题，我们还是希望尽量不采用session机制
		if (session != null) {
			session.invalidate();
		}
		ctx.deleteUserInCookie();
		ctx.redirect("/");
	}

	public void login(RequestContext ctx) throws IOException {
		String email = ctx.param("email", "").trim();
		String pwd = ctx.param("pwd", "").trim();
		User user = User.Login(email, pwd, ctx.ip());
		if (user == null) {
			throw new ActionException("login fail");
		}
		ctx.saveUserInCookie(user, true);
	}

	public void reg(RequestContext ctx) throws IOException {
		String email = ctx.param("email", "").trim();
		String uname = ctx.param("uname", "").trim();
		String pwd = ctx.param("pwd", "").trim();
		if(StringUtils.isBlank(email)||StringUtils.isBlank(uname)||StringUtils.isBlank(pwd)){
			throw new ActionException("All fields required");
		}
		User user = new User();
		user.setEmail(email);
		user.setName(uname);
		// 加密
		user.setPwd(DigestUtils.shaHex(pwd));
		user.setThis_login_ip(ctx.ip());
		user.Save();
		ctx.saveUserInCookie(user, true);
	}

	public void destroy() {
		System.out.println("-----------------UserAction.destroy at "
				+ new Date());
	}
}
